// pages/personal/wallet/wallet.js
const personal = require('../../../api/personal.js')
const payPasswordApi = require('../../../api/pay_password.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    balance: '',
    pay_password: '',
    show: false,
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('load')
    wx.showLoading({
      title: '正在加载',
    })
  },
  // 获取余额
  getBalance(token) {
    personal.getUserInfo(token).then(res => {
      if (res.data.code == 0) {
        this.setData({
          balance: res.data.data.balance,
          pay_password: res.data.data.pay_password
        })
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log('show')
    let token = wx.getStorageSync('token')
    this.getBalance(token)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  onClose(event) {
    if (event.detail === 'confirm') {
      // 异步关闭弹窗
      setTimeout(() => {
        this.setData({
          show: false
        });
      }, 1000);
    } else {
      this.setData({
        show: false
      });
    }
  },
  showCustomDialog() {
    this.setData({
      show: true
    });
  },
  onChange(e) {
    this.setData({
      password: e.detail
    })
  },
  onChange2(e) {
    this.setData({
      password2: e.detail
    })
  },
  // 跳转充值界面
  topUp: function() {
    if (!this.data.pay_password) {
      this.showCustomDialog()
    } else {
      wx.navigateTo({
        url: './balance/balance',
      })
    }
  },
  onConfirm() {
    let that = this
    let token = wx.getStorageSync('token')
    let password = this.data.password
    let password2 = this.data.password2
    if (password && password2) {
      if (password == password2) {
        let data = {
          pay_password: password
        }
        let token = wx.getStorageSync('token')
        payPasswordApi.modifyPayPassword(data, token).then(res => {
          if(res.data.code == 0) {
            wx.showToast({
              title: '密码设置成功',
            })
            that.getBalance(token)
          }
        })
      } else {
        wx.showToast({
          title: '密码不一致',
          icon: 'none'
        })
      }
      this.setData({
        password: '',
        password2: ''
      })
    }else {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none'
      })
    }
  }
})